﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using GalaSoft.MvvmLight;

namespace BingleMaps.Models
{
	public class UserPinLog : ViewModelBase
	{
		public Collection<UserPinChange> Changes { get; private set; }

		private ObservableCollection<UserPin> _pins;
		public ObservableCollection<UserPin> Pins
		{
			get { return _pins; }
			set
			{
				if (value == _pins) return;
				_pins = value;
				RaisePropertyChanged("Pins");
			}
		}

		public UserPinLog()
		{
			Changes = new Collection<UserPinChange>();
			Pins = new ObservableCollection<UserPin>();
		}

		public void Add(UserPin pin)
		{
			pin.Key = Guid.NewGuid();
			Pins.Add(pin);
			Changes.Add(new UserPinChange { Key = pin.Key, Action = UserPinAction.Add });
		}

		public void Remove(Guid key)
		{
			var pin = GetPin(key);
			var change = GetChange(key);

			if (pin != null && change != null)
			{
				Pins.Remove(pin);
				Changes.Remove(change);
			}
			else if (pin == null && change != null)
				change.Action = UserPinAction.Delete;
			else if (pin != null)
			{
				Pins.Remove(pin);
				Changes.Add(new UserPinChange { Action = UserPinAction.Delete, Key = pin.Key });
			}
		}

		public void RemoveCheckedPins()
		{
			for (var i = Pins.Count - 1; i >= 0; i--)
				if (Pins[i].IsChecked)
					Pins.RemoveAt(i);
		}

		public UserPin GetPin(Guid key)
		{
			return Pins.FirstOrDefault(item => item.Key == key);
		}

		public UserPinChange GetChange(Guid key)
		{
			return Changes.FirstOrDefault(item => item.Key == key);
		}
	}
}
